package cn.zwt.wolf.listener;

import cn.zwt.wolf.constant.GlobleConstant;
import cn.zwt.wolf.convert.RuleInfoConvert;
import cn.zwt.wolf.domain.arrange.Arrange;
import cn.zwt.wolf.domain.arrange.ArrangeItem;
import cn.zwt.wolf.domain.content.Content;
import cn.zwt.wolf.domain.position.Position;
import cn.zwt.wolf.domain.position.PositionItem;
import cn.zwt.wolf.domain.rule.Rule;
import cn.zwt.wolf.service.arrange.ArrangeItemService;
import cn.zwt.wolf.service.arrange.ArrangeService;
import cn.zwt.wolf.service.content.ContentService;
import cn.zwt.wolf.service.position.PositionItemService;
import cn.zwt.wolf.service.position.PositionService;
import cn.zwt.wolf.service.rule.RuleService;
import cn.zwt.wolf.util.JacksonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangwt on 16-3-13.
 */
@Component
public class RuleListener {
    @Autowired
    private RuleService ruleService;
    @Autowired
    private ArrangeService arrangeService;
    @Autowired
    private ArrangeItemService arrangeItemService;
    @Autowired
    private ContentService contentService;
    @Autowired
    private PositionService positionService;
    @Autowired
    private PositionItemService positionItemService;

    private Logger logger = LoggerFactory.getLogger(RuleListener.class);

    /**
     * 接受消息
     * @param message
     */
    public void onListen(Object message) {
        logger.info("***********get rule message ********");
        try {
            Rule rule = JacksonUtils.jsonStringToObject(message.toString(),Rule.class);
            if (rule.getContainer_type()==0){//推荐位
                runPositionRule(rule);
            }else if (rule.getContainer_type()==1){//编排
                runArrangeRule(rule);
            }

        } catch(Exception e){
            e.printStackTrace();
        }
        logger.info("***********end rule message ********");
    }
/**
 * status:=:Integer:1;areaCode:in:String:zhongguodalu;
 * languageCode:in:String:yingyu;tagCode:in:String:juqing;
 * score:>:Float:2.0;score:<:Float:4.0;year:>:Integer:2000;year:<:Integer:2016;
 * */
    public void runArrangeRule(Rule rule){
        logger.info("***********runArrangeRule begin ********");
        Arrange arrange=this.saveArrange(rule);
        this.initArrangeItem(arrange);
        logger.info("***********runArrangeRule end ********");
    }
    /**
     * 将rule 存为Arrange
     * */
    public Arrange saveArrange(Rule rule){
        Arrange old_arrange = arrangeService.findArrangeByRid(rule.getId());
        Arrange arrange = RuleInfoConvert.convertRule2Arrange(rule,old_arrange);
        return arrangeService.saveOrUpdate(arrange);
    }

    /**
     * 通过value查询出相应的节目然后存入item　
     * */
    public void initArrangeItem(Arrange arrange){
       if (arrange!=null){
           Rule rule = ruleService.findRuleById(arrange.getRuleId());
           List<ArrangeItem> arrangeItems = arrangeItemService.findArrangeItemByPage(arrange);
           if (arrangeItems!=null && arrangeItems.size()>0){
               for (ArrangeItem arrangeItem:arrangeItems){
                   arrangeItem.setStatus(GlobleConstant.STATUS_DELETE);
                   arrangeItemService.deleteItem(arrangeItem);
               }
           }

           String values = null;
           Map<String,Object> params = new HashMap<String ,Object>();
           if (rule != null){
               values= rule.getRule_value();
               String[] value = values.split(";");
               for (String str:value){
                   String[] nodes = str.split(":");
                   if (nodes.length==4){
                       if ("status".equals(nodes[0])){
                           params.put("status",nodes[3]);
                           continue;
                       }
                       if ("areaCode".equals(nodes[0])){
                           params.put("areaCode",nodes[3]);
                           continue;
                       }
                       if ("tagCode".equals(nodes[0])){
                           params.put("tagCode",nodes[3]);
                           continue;
                       }
                       if ("tagCode".equals(nodes[0])){
                           params.put("languageCode",nodes[3]);
                           continue;
                       }
                       if("score".equals(nodes[0])){
                           if (nodes[1].equals("<")){
                               params.put("endScore",nodes[3]);
                               continue;
                           }
                           if (nodes[1].equals(">")){
                               params.put("startScore",nodes[3]);
                               continue;
                           }
                       }
                       if("year".equals(nodes[0])){
                           if (nodes[1].equals("<")){
                               params.put("endYear",nodes[3]);
                               continue;
                           }
                           if (nodes[1].equals(">")){
                               params.put("startYear",nodes[3]);
                               continue;
                           }
                       }
                   }
               }
               params.put("order",rule.getRule_order());
           }
           List<Content> contents= contentService.queryListForArrange(params);
           if (contents!=null){
               for (Content content:contents){
                   ArrangeItem arrangeItem=arrangeItemService.changeContentToArrangeItem(content,new ArrangeItem(),arrange.getCode());
                   arrangeItemService.saveOrUpdate(arrangeItem);
               }
           }
       }
    }
    public void runPositionRule(Rule rule){
        logger.info("***********runPositionRule begin ********");
        Position position=this.savePosition(rule);
        this.initPositionItem(position);
        logger.info("***********runPositionRule end ********");
    }
    public Position savePosition(Rule rule){
        Position old_position = positionService.findPositionByCode(rule.getCode());
        Position new_position = RuleInfoConvert.convertRule2Position(rule, old_position);
        return positionService.saveOrUpdate(new_position);
    }
    public void initPositionItem(Position position){
        if (position!=null){
            Rule rule = null;
            if (position.getParentId()==0) {
                 rule = ruleService.findRuleByCode(position.getCode());
            }
            else{
                Position position_father = positionService.findPositionById(position.getParentId());
                rule = ruleService.findRuleByCode(position_father.getCode());
            }

            String values = null;
            Map<String,Object> params = new HashMap<String ,Object>();
            if (rule != null){
                values= rule.getRule_value();
                String[] value = values.split(";");
                for (String str:value){
                    String[] nodes = str.split(":");
                    if (nodes.length==4){
                        if ("status".equals(nodes[0])){
                            params.put("status",nodes[3]);
                            continue;
                        }
                        if ("areaCode".equals(nodes[0])){
                            params.put("areaCode",nodes[3]);
                            continue;
                        }
                        if ("tagCode".equals(nodes[0])){
                            params.put("tagCode",nodes[3]);
                            continue;
                        }
                        if ("tagCode".equals(nodes[0])){
                            params.put("languageCode",nodes[3]);
                            continue;
                        }
                        if ("length".equals(nodes[0])){
                            params.put("length",nodes[3]);
                            continue;
                        }
                        if("score".equals(nodes[0])){
                            if (nodes[1].equals("<")){
                                params.put("endScore",nodes[3]);
                                continue;
                            }
                            if (nodes[1].equals(">")){
                                params.put("startScore",nodes[3]);
                                continue;
                            }
                        }
                        if("year".equals(nodes[0])){
                            if (nodes[1].equals("<")){
                                params.put("endYear",nodes[3]);
                                continue;
                            }
                            if (nodes[1].equals(">")){
                                params.put("startYear",nodes[3]);
                                continue;
                            }
                        }
                    }
                }
                params.put("order",rule.getRule_order());
            }
            List<Content> contents= contentService.queryListForArrange(params);
            if (contents!=null){
                for (Content content:contents){
                    PositionItem positionItem=positionItemService.changeContentToPositionItem(content, new PositionItem(), position.getCode());
                    positionItemService.saveOrUpdate(positionItem);
                }
            }
        }
    }

}
